/**
 * 
 */
package org.lookouster.nextAgadir.pointageBureau.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

import org.lookouster.nextAgadir.pointageBureau.bases.Qualification;
import org.lookouster.nextAgadir.pointageBureau.outils.BDConnect;
import org.lookouster.nextAgadir.pointageBureau.outils.BDFunctions;
import org.lookouster.nextAgadir.pointageBureau.outils.functions;

/**
 * @author Lookouster
 *
 */
/*
 * Qualifications.java
 *
 * Created on 30 avril 2008, 00:59
 */

public class GestionQualifs extends javax.swing.JDialog {
    
    /** Creates new form Qualifications */
    public GestionQualifs(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
    }
    

    private void initComponents() {

    	jScrollPane1 = new javax.swing.JScrollPane();
        qualif = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        
        btn1Mode=0;
        btn2Mode=0;
        btn3Mode=0;
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        

        
        
        
        try {
			allQualifications=BDFunctions.getQualificationList();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			allQualifications=new ArrayList<Qualification>();
			functions.affiche("pb getQualif List: "+e.getMessage());
			return;
		}
		
		if(allQualifications==null)
			allQualifications=new ArrayList<Qualification>();
        
        jScrollPane1.setViewportView(qualif);
        
        
        
        
        jLabel1.setText(UICommons.fQualifTitle);
        
        jButton2.setText(UICommons.btnDel);
        jButton1.setText(UICommons.btnadd);
        
        jButton2.setEnabled(false);
        
        jButton3.setText(UICommons.btnClose);
        
        
        jButton1.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				execAppropriate1();
			}
        	
        });
        
        jButton2.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				execAppropriate2();
			}
        	
        });
        
        jButton3.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				execAppropriate3();
			}
        	
        });
		
		reloadQualifTable();
		
		qualif.setSelectionMode(0);
		qualif.getSelectionModel().addListSelectionListener(new ListSelectionListener()
		{

			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				// TODO Auto-generated method stub
				loadQualifDatas();
			}
			
		});
		
       

         
        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(104, 104, 104)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextField1, 150, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                            		.addComponent(jButton1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton2, 100, 110, 120)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton3, 100, 110, 120)))
                            //.addComponent(jButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addComponent(jLabel1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(57, 57, 57)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1)
                                .addComponent(jButton2)
                                .addComponent(jButton3, 26,26,26)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(33, 33, 33)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(66, Short.MAX_VALUE))
        );
       
        pack();
       
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            	GestionQualifs dialog = new GestionQualifs(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
               dialog.setVisible(true);
            }
        });
    }
    
    
    
    /**
     * Populate the Qualification Table
     */
    public void reloadQualifTable()
    {
    	
		
    	if(!allQualifications.isEmpty())
    	{
    		qualif.setModel(new QualifModel(allQualifications));
    	}
    }
    
    /**
     * Qualifications' Table Model Class
     * @author Lookouster
     *
     */
    class QualifModel implements TableModel
    {
    	
    	List<Qualification> results;
    	
    	public QualifModel(List<Qualification> ql)
    	{
    		results=ql;
    	}

		@Override
		public void addTableModelListener(TableModelListener l) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public Class<?> getColumnClass(int columnIndex) {
			// TODO Auto-generated method stub
			 return getValueAt(0, columnIndex).getClass();
		}

		@Override
		public int getColumnCount() {
			// TODO Auto-generated method stub
			return UICommons.QualifTableFields.length;
		}

		@Override
		public String getColumnName(int columnIndex) {
			// TODO Auto-generated method stub
			return UICommons.QualifTableFields[columnIndex];
		}

		@Override
		public int getRowCount() {
			// TODO Auto-generated method stub
			return results.size();
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			switch(columnIndex)
			{
			case 0:return results.get(rowIndex).getIdQualification();
			case 1: return results.get(rowIndex).getLibelle();
			default: return "???";
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void removeTableModelListener(TableModelListener l) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void setValueAt(Object value, int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			
		}
    	
    }
    
    /**
     * Executed when a table item is selected
     */
    public void loadQualifDatas()
    {
    	if(qualif.getSelectedRow()==-1)
    		return;
    	jTextField1.setEditable(false);
    	jButton1.setText(UICommons.btnEdit);
    	jButton2.setEnabled(true);
    	//jButton2.setText(UICommons.btnDel);
    	jButton3.setText(UICommons.btnNew);
    	jTextField1.setText(allQualifications.get(qualif.getSelectedRow()).getLibelle());
    	btn1Mode=1;//Editability
    	btn2Mode=1;//Delete?
    	btn3Mode=1;//Back to new
    }
    
    
    
    /**
     * Choose the right action when button 1 is clicked
     */
    public void execAppropriate1()
    {
    	if(!isTextFieldOk())
		{
			JOptionPane.showMessageDialog(this,UICommons.fQualifLibEmpty);
			return;
		}
    	if(btn1Mode==0)
    	{
    		//System.out.println("mode1: "+btn1Mode);
    		
			try {
				BDConnect bdc = new BDConnect();
				//TODO if empty
				if(jTextField1.getText().trim().length()==0)
				{
					JOptionPane.showMessageDialog(this, UICommons.fQnotifLib);
					return;
				}
				Qualification tmp=new Qualification(jTextField1.getText());
	    		if(tmp.saveDB(bdc))
	    		{
	    			allQualifications.add(tmp);
	    			reloadQualifTable();
	    			JOptionPane.showMessageDialog(this,UICommons.fQSuccess);
	    		}
	    		else
	    		{
	    			//System.out.println("pbdmrd");
	    			JOptionPane.showMessageDialog(this,UICommons.fQFail2);
	    		}
	    		
	    		//bdc.shutdown();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			resetUI();
    		return;
    	}
    	else if(btn1Mode==1)
    	{
    		//unlock the text field
    		jTextField1.setEditable(true);
    		btn1Mode=2;
    		qualif.setEnabled(false);
    		jButton1.setText(UICommons.btnValid);
    		jButton3.setText(UICommons.btnCancel);
    		btn3Mode=1;
    		return;
    	}
    	else if(btn1Mode==2)
    	{
    		
    		try {
				BDConnect bdc=new BDConnect();
				int pos=qualif.getSelectedRow();
				String tmp=allQualifications.get(pos).getLibelle();
				allQualifications.get(pos).setLibelle(
						jTextField1.getText().trim());
				if(allQualifications.get(pos).updateDB(bdc))
				{
					reloadQualifTable();
					JOptionPane.showMessageDialog(this,UICommons.fQSuccess);
				}
				else
	    		{
					allQualifications.get(pos).setLibelle(tmp);
	    			JOptionPane.showMessageDialog(this,UICommons.fQFail2);
	    		}
					
				bdc.shutdown();
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		qualif.setEnabled(true);
    		btn1Mode=0;
    		btn2Mode=0;
    		btn3Mode=0;
    	}
    }
    
    
    public void  execAppropriate2()
    {
    	if(btn2Mode==1)
    	{
    		BDConnect bdc;
			try {
				bdc = new BDConnect();
				Qualification tmp=allQualifications.get(
	    				qualif.getSelectedRow()); 
				qualif.getSelectionModel().clearSelection();
				if(BDFunctions.deleteQualif(tmp.getIdQualification(),bdc))
				{
					allQualifications.remove(tmp);
					JOptionPane.showMessageDialog(this,
							UICommons.fQualifDelSucc);
					reloadQualifTable();
				}
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				JOptionPane.showMessageDialog(this,UICommons.fQualifDelPb);
			}
    	
    	}
    	resetUI();
    }
    
    public void execAppropriate3()
    {
    	if(btn3Mode==0)
    	{
    		this.setVisible(false);
    	}
    	else if(btn3Mode==1)
    	{
    		resetUI();
    	}
    }
    
    public boolean isTextFieldOk()
    {
    	if(jTextField1.getText().trim().length()==0)
    		return false;
    	return true;
    }
    
    
    public void resetUI()
    {
    	jTextField1.setText("");
    	jTextField1.setEditable(true);
    	qualif.setEnabled(true);
    	qualif.getSelectionModel().clearSelection();
    	jButton2.setEnabled(false);
    	jButton1.setText(UICommons.btnadd);
    	jButton3.setText(UICommons.btnClose);
    	btn1Mode=0;
    	btn2Mode=0;
    	btn3Mode=0;
    }
    
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1, jButton2, jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable qualif;
    private javax.swing.JTextField jTextField1;
    private List<Qualification> allQualifications;
    private int btn1Mode, btn2Mode, btn3Mode;
    /*btn1Mode 	0	Add new
       			2 	Set editable
       			3	Edit Existing
      btn2Mode	0	Deactivate
      			1	Delete Existing
      			
      btn3Mode	0	Close Dialog
      			1	Back to new*/
    // End of variables declaration
    
}
